{% extends 'base.html' %}
{% block content %}

<h3>上传知识库文件</h3>
<form action="{{ url_for('upload_file') }}" method="post" enctype="multipart/form-data">
  <input type="file" name="file" required>
  <button type="submit">上传</button>
</form>
<hr>

<h3>发表留言</h3>
<form method="post" action="{{ url_for('add_message') }}">
  <textarea name="body" class="form-control mb-2" rows="3" required></textarea>
  <button class="btn btn-success">提交</button>
</form>
<hr>
<h4>历史留言</h4>
{% for m in msgs %}
<div class="card mb-3">
  <div class="card-header">
    <strong>{{ m.author.username }}</strong> · {{ m.created.strftime('%Y-%m-%d %H:%M') }}
  </div>
  <div class="card-body">
    <div class="mb-2">{{ m.body }}</div>
    <div id="ai-{{ m.id }}" class="markdown-body">{% if m.ai_reply %}{{ m.ai_reply }}{% else %}
      <button class="btn btn-sm btn-outline-primary"
              onclick="askAI({{ m.id }})">获取方案</button>
    {% endif %}</div>
  </div>
</div>
{% endfor %}

<!-- 1. 引入 Markdown 渲染器 -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5/github-markdown-light.css">

<script>
function askAI(id){
  const box = document.getElementById('ai-'+id);
  box.innerHTML = '正在输入…';
  const es = new EventSource(`/reply/${id}`);
  let buf = '';
  es.onmessage = e => {
    const d = JSON.parse(e.data);
    buf += d.content;
    box.innerHTML = marked.parse(buf);   // 2. 实时解析 Markdown
  };
  es.onerror = () => es.close();
}
</script>
{% endblock %}